package com.jijuxie.system.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jijuxie.common.exception.BusinessException;
import com.jijuxie.common.utils.SecurityUtils;
import com.jijuxie.system.domain.SysUser;
import com.jijuxie.system.domain.dto.UpdateUserInfoDTO;
import com.jijuxie.system.mapper.SysUserMapper;
import com.jijuxie.system.service.IUserService;
import org.apache.commons.lang3.StringUtils;

@Service
public class UserServiceImpl implements IUserService {
    
    @Autowired
    private SysUserMapper userMapper;

    @Override
    public SysUser getUserById(Long userId) {
        return userMapper.selectById(userId);
    }

    @Override
    public SysUser getUserByUsername(String username) {
        return userMapper.selectByUsername(username);
    }

    @Override
    public SysUser getUserByPhone(String phone) {
        return userMapper.selectByPhone(phone);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUserInfo(Long userId, UpdateUserInfoDTO updateDTO) {
        SysUser user = userMapper.selectById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        
        // 验证手机号是否被其他用户使用
        if (StringUtils.isNotBlank(updateDTO.getPhone()) 
                && !updateDTO.getPhone().equals(user.getPhoneNumber())) {
            SysUser existingUser = userMapper.selectByPhone(updateDTO.getPhone());
            if (existingUser != null && !existingUser.getUserId().equals(userId)) {
                throw new BusinessException("手机号已被其他用户使用");
            }
        }
        
        // 验证邮箱是否被其他用户使用
        if (StringUtils.isNotBlank(updateDTO.getEmail()) 
                && !updateDTO.getEmail().equals(user.getEmail())) {
            SysUser existingUser = userMapper.selectByEmail(updateDTO.getEmail());
            if (existingUser != null && !existingUser.getUserId().equals(userId)) {
                throw new BusinessException("邮箱已被其他用户使用");
            }
        }
        
        // 更新用户信息
        if (StringUtils.isNotBlank(updateDTO.getRealName())) {
            user.setRealName(updateDTO.getRealName());
        }
        if (StringUtils.isNotBlank(updateDTO.getPhone())) {
            user.setPhoneNumber(updateDTO.getPhone());
        }
        if (StringUtils.isNotBlank(updateDTO.getEmail())) {
            user.setEmail(updateDTO.getEmail());
        }
        if (StringUtils.isNotBlank(updateDTO.getAvatar())) {
            user.setAvatar(updateDTO.getAvatar());
        }
        if (StringUtils.isNotBlank(updateDTO.getSex())) {
            user.setSex(updateDTO.getSex());
        }
        
        userMapper.updateById(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePassword(Long userId, String oldPassword, String newPassword) {
        SysUser user = userMapper.selectById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        
        // 验证旧密码
        if (!SecurityUtils.matchesPassword(oldPassword, user.getPassword())) {
            throw new BusinessException("原密码错误");
        }
        
        // 验证新密码
        SecurityUtils.validatePassword(newPassword);
        
        // 更新密码
        user.setPassword(SecurityUtils.encryptPassword(newPassword));
        userMapper.updateById(user);
    }

    @Override
    public SysUser validateCredentials(String username, String password) {
        SysUser user = userMapper.selectByUsername(username);
        if (user == null || !SecurityUtils.matchesPassword(password, user.getPassword())) {
            return null;
        }
        return user;
    }

    @Override
    public SysUser registerByPhone(String phone) {
        SysUser user = new SysUser();
        user.setPhoneNumber(phone);
        user.setUsername(phone); // 使用手机号作为用户名
        user.setNickName("用户" + phone.substring(7)); // 使用手机号后4位作为默认昵称
        user.setPassword(SecurityUtils.encryptPassword(phone.substring(5))); // 使用手机号后6位作为初始密码
        user.setStatus("0"); // 正常状态
        user.setDelFlag("0"); // 未删除
        
        userMapper.insert(user);
        return user;
    }
} 